package com.css.fxfzaqbz.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.css.fxfzaqbz.common.utils.ssl.TrustAnyHostnameVerifier;
import com.css.fxfzaqbz.common.utils.ssl.TrustAnyTrustManager;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class LocationUtil {

    /**
     * 给定经纬度定位区划信息
     *
     * @param lon, lat
     * @return Map<String, String>
     */
    public static Map<String, String> getLocationInfoByTD(double lon, double lat) {
        Map<String, String> result = new HashMap<String, String>();
        String path = "http://api.tianditu.gov.cn/geocoder?postStr={'lon':" + lon + ",'lat':" + lat + ",'ver':1}&type=geocode&tk=d21000f516e20e56b2a2b50596ecc1ee";
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //conn.setRequestMethod("POST");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            PrintWriter out = new PrintWriter(conn.getOutputStream());
            //out.print(data);
            out.flush();
            InputStream is = conn.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String str = br.readLine();
            JSONObject json = JSONObject.parseObject(str);
            JSONObject aComponent = json.getJSONObject("result").getJSONObject("addressComponent");
            result.put("nation", aComponent.getString("nation"));
            result.put("province", aComponent.getString("province"));
            result.put("city", aComponent.getString("city"));
            result.put("county", aComponent.getString("county"));
            result.put("address", aComponent.getString("address"));
            is.close();
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    public static Map<String, String> getLocationInfoByAMap(double lon, double lat) {
        Map<String, String> result = new HashMap<String, String>();
        String path = "https://restapi.amap.com/v3/geocode/regeo?output=JSON&location=" + lon + "," + lat + "&key=c69fc327d869273de11743d6b929d961&radius=1000";
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //conn.setRequestMethod("POST");
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            PrintWriter out = new PrintWriter(conn.getOutputStream());
            //out.print(data);
            out.flush();
            InputStream is = conn.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String str = br.readLine();
            JSONObject json = JSONObject.parseObject(str);
            JSONObject aComponent = json.getJSONObject("regeocode").getJSONObject("addressComponent");
            result.put("country", aComponent.getString("country"));
            result.put("province", aComponent.getString("province"));
            result.put("city", aComponent.getString("city"));
            result.put("district", aComponent.getString("district"));
            result.put("township", aComponent.getString("township"));
            is.close();
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static Map<String, String> getGPositionByTD(double lon, double lat) {
        Map<String, String> result = new HashMap<String, String>();
        String path = "https://fxpc.mem.gov.cn/data_preparation/171dd1d5-bbb3-483a-a7f6-50d6d98cee1f/7a55d40f-b5e2-4888-a94e-f874693e8d0e/gposition?lon=" + lon + "&lat=" + lat + "&type=1&geokey=94E99EB4FEB9B48CD5348F7BCF5BB620";
        //System.out.println(path);
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

            URL url = new URL(path);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setSSLSocketFactory(sc.getSocketFactory());
            conn.setHostnameVerifier(new TrustAnyHostnameVerifier());

            conn.setDoOutput(false);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setConnectTimeout(1000 * 100);
            conn.setReadTimeout(1000 * 100);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "*/*");
            conn.setRequestProperty("Connection", "keep-alive");
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            conn.setRequestProperty("Charset", "UTF-8");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            conn.connect();

            InputStream input = null;
            if(conn.getResponseCode()==200){
                input = conn.getInputStream();
            }else{
                input = conn.getErrorStream();
            }
            BufferedReader br = new BufferedReader(new InputStreamReader(input, "UTF-8"));
            StringBuffer buffer = new StringBuffer();
            String line = null;
            while ((line = br.readLine()) != null) {
                buffer.append(line);
            }
            JSONObject json = JSONObject.parseObject(buffer.toString());
            JSONObject aComponent = json.getJSONObject("data");
            result.put("province", aComponent.getString("sheng_name"));
            result.put("city", aComponent.getString("shi_name"));
            result.put("county", aComponent.getString("xian_name"));
            result.put("address", aComponent.getString("xiang_name"));
            br.close();
            input.close();
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    public static void main(String[] args) {
        double lon = 116.37304, lat = 39.92594;//119.37304,35.22594  116.37304, 39.92594
        //Map<String, String> result = getLocationInfoByAMap(lon, lat);
        //Map<String, String> result = getLocationInfoByTD(lon, lat);
        Map<String, String> result = getGPositionByTD(lon, lat);
        for (Map.Entry<String, String> entry : result.entrySet()) {
            //System.out.println(entry.getKey() + " : " + entry.getValue());
        }
    }

}
